﻿#region MIT License
/*

Copyright (C) 2011 by Timothy A. Barela

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
#endregion

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Mono.Cecil;
using LineCommander;

namespace Sharpener
{
	public static class Program
	{
		public const string ApplicationName = "sharpener";

		public static int Main(string[] args)
		{
			int result=0;
			//args = new string[0]; 

			try
			{
				var cmd = new SharpenerCommandLine();
				cmd.Parse(args);
				
				var optimizer = createOptimizer(cmd);
				string input;

				if(cmd.HasValues)
					input = GetCaseSensitiveFullPath(cmd.Values[0]);
				else
					throw new Exception("No input filename was given.");

				if(string.IsNullOrEmpty(cmd.Out))
				{
					cmd.Out=GetDefaultOutputPath(input);
				}

				cmd.Print("Sharpening assembly '{0}'",input);

				var ass = AssemblyDefinition.ReadAssembly(input);

				if(optimizer.Optimize(ass))
				{
					cmd.Print("Saving assembly to '{0}'",cmd.Out);

					//Safeguards against an exception in case target folder doesnt exist
					var dir = Path.GetDirectoryName(cmd.Out);

					if(dir != "")
					{
						if(!Directory.Exists(dir))
						{
							Directory.CreateDirectory(dir);
						}
					}

					ass.Write(cmd.Out);
				}
				else
				{
					cmd.Print("No modifications were made to the assembly.");
					if(input != cmd.Out)
					{
						cmd.Print("Copying assembly to '{0}'",cmd.Out);
						File.Copy(input,cmd.Out,true);
					}
				}
			}
			catch(CommandLineNoInputException cliex)
			{
				var cmd = (SharpenerCommandLine)cliex.CommandLine;
				cmd.Quiet = false;
				cmd.Print(cmd.GetHeadingString());
				cmd.Print("Error: No inputs.\n");
				cmd.Print(cmd.GetUsageString());
				cmd.Print("\nWhere [options] are:\n");
				cmd.Print(cmd.GetHelpString());

				result = 1;
			}
			catch(CommandLineException clex)
			{
				Console.WriteLine(clex.Message);

				var cmd = (SharpenerCommandLine)clex.CommandLine;
				cmd.Quiet = false;
				cmd.Print(cmd.GetUsageString());

				result = 1;
			}
			catch(Exception ex)
			{
				Console.WriteLine("Error: {0}",ex.Message);
				result = 1;
			}

			Console.WriteLine(result==0?"Success.":"Failed.");
#if DEBUG
			Console.WriteLine("Press enter.");
			Console.ReadLine();
#endif
			return result;
		}

		private static AssemblyOptimizer createOptimizer(SharpenerCommandLine cmd)
		{
			var optimizer = new AssemblyOptimizer();
			
			cmd.Print(cmd.GetHeadingString());

			if(cmd.Values.Count != 1)
				throw new CommandLineException(cmd,"No input assembly was specified.");

			if(cmd.Quiet)
				optimizer.TextWriter = TextWriter.Null;

			if(cmd.All || cmd.StripCallVirt)
				optimizer.Passes.Add(new StripCallVirtPass());

			if(cmd.All || cmd.ForceInline)
				optimizer.Passes.Add(new MethodInliningPass());

			if(cmd.All || cmd.Watermark)
				optimizer.Passes.Add(new WatermarkPass());

			if(cmd.All || cmd.InlineValueTypeOperators)
				Debug.Print("Attempted to enable inlining of value type operators.");

			if(optimizer.Passes.Count == 0)
			{
				//treat as --all
				optimizer.Passes.AddRange(new Pass[]
					{
						new StripCallVirtPass(),
						new MethodInliningPass(),
						new WatermarkPass(),
					});
			}

			//always remove references to sharpener??.. this is fairly tied to forceinline,
			//we *MUST* rethink this, because if forceinline doesnt run, this will screw with
			//the forceinline attributes by taking away the required assembly reference....
			bool requiresRemoveReferencePass=false;

			foreach(var pass in optimizer.Passes)
			{
				if(pass is MethodInliningPass)
				{
					requiresRemoveReferencePass = true;
					break;
				}
			}

			if(requiresRemoveReferencePass)
				optimizer.Passes.Add(new RemoveSharpenerReferencePass());
									
			return optimizer;
		}
	
		public static string GetDefaultOutputPath( string inputFilePath )
		{
			//The following code writes back the same file with "Optimized" appended to the 
			//file name. Not sure if I like this...
			//Need to decide whether overwriting the original assembly should be so easy...
			var dir = Path.GetDirectoryName(inputFilePath); 
			var name = Path.GetFileNameWithoutExtension(inputFilePath);
			var ext = Path.GetExtension(inputFilePath);
			var outputPath = Path.Combine(dir, name + "Optimized" + ext);

			return outputPath;
		}

		public static string GetCaseSensitiveFullPath( string path )
		{
			//this method expects the file to exist on the filesystem
			if(!File.Exists(path))
				throw new FileNotFoundException(string.Format("Unable to find file '{0}'.",
																path));

			path = Path.GetFullPath(path);
			var files = Directory.GetFiles(Path.GetDirectoryName(path), Path.GetFileName(path));

			if(files != null)
			{
				return files[0];
			}

			return path;//*shrugs*
		}
	}
}